"""
    Controller for editing new agreement, based on `student_migration_for_admin` view.
"""

import datetime
from mnemoply import model
from mnemoply.controllers.lookup import LookupController, TableCol, TableLookupDataSource
from mnemoply.controllers.StudentAgreement import AgreementController, EducationInfoTab
from mnemoply.controllers.crud import CRUDController
from mnemoply.mass_actions import MassAction, MassActionForm
from mnemoply.widgets import GroupField

def currentYear():
    return datetime.date.today().year

def currentGroupYear():
    """On summer'10 returns 2009"""
    return datetime.date.today().year - 1

# It's temporary workaround for group creation in summer
# class MAGroupTransferWithoutOrder(MassAction):
#     target_class = model.StudentAgreement
#     name = "group_transfer_without_order"
#     title = _("Switch group")

#     form = MassActionForm(name=name, fields=[createGroupField(currentYear())])

#     def call(self, objs, group_id):
#         group = model.Group.get(int(group_id))

#         for agr in objs:
#             for sig in model.StudentInGroup.selectBy(studentAgreement=agr):
#                 sig.group = group

class MAFillPlans(MassAction):
    target_class = model.StudentAgreement
    name = "fill_plans"
    title = _("Fill plans")

    def call(self, objs):
        current_year = currentGroupYear()
        m = model.StudentMigration
        for agr in objs:
            possible_migrations = list(m.select(m.q.studentID == agr.student.id))
            possible_migrations = [m for m in possible_migrations
                                   if m is not None
                                   and m.groupFrom is not None
                                   and m.groupFrom.year == current_year]  # TODO

            if len(possible_migrations):
                migration = possible_migrations[0]
                if migration.initialPlanTeacherWish == agr.initialPlanStudentWish:
                    agr.initialPlan = agr.initialPlanStudentWish
                elif migration.initialPlanMethodologistWish is not None:
                    agr.initialPlan = migration.initialPlanMethodologistWish
                else:
                    self.successfully_execute = False
            else:
                self.successfully_execute = False

class MAMigrationGroupInclusion(MassAction):
    target_class = model.StudentAgreement
    name = "migration_group_inclusion"
    title = _("Group inclusion")
    form = MassActionForm(name=name, fields=[
            GroupField(
                name="group_id",
                not_empty=True,
                label="In group",
                ),
            ])

    def call(self, objs, group_id):
        group = model.Group.get(int(group_id))
        current_year = currentGroupYear()
        m = model.StudentMigration

        for agr in objs:
            possible_migrations = list(m.select(m.q.studentID == agr.student.id))
            possible_migrations = [m for m in possible_migrations
                                   if m is not None
                                   and m.groupFrom is not None
                                   and m.groupFrom.year == current_year]  # TODO

            not_in_group = len(list(model.StudentInGroup.selectBy(group=group, studentAgreement=agr))) == 0

            if not group.isOverSizedGroup() \
                    and agr.initialPlan == group.initialPlan \
                    and agr.organization == group.organization \
                    and agr.customerTariff == group.customerTariff \
                    and not_in_group:
                student = agr.student
                order = model.Order.get(1)
                group.includeStudent(student, order, agr)
                if len(possible_migrations):
                    possible_migrations[0].groupCacheTitle = group.title
            else:
                self.successfully_execute = False

class MigrationForAdminController(LookupController, CRUDController):
    model_object = model.StudentAgreement

    lookup_columns = [
        TableCol(name='student', caption=_('Student')),
        TableCol(name='group_title', caption=_('Group NEXT')),
        TableCol(name='school_form', caption=_('School form')),
        TableCol(name='student_wish_plan', caption=_('Initial plan student wish')),
        TableCol(name='teacher_plan', caption=_('Teacher wish plan')),
        TableCol(name='methodologist_plan', caption=_('Methodologist wish plan'), hidden=True),
        TableCol(name='initial_plan', caption=_('Result plan')),
        TableCol(name='migration_plan', caption=_('Migration plan'), hidden=True),
        TableCol(name='possible_day', caption=_('Possible day'), hidden=True),
        TableCol(name='unpossible_day', caption=_('Unpossible day'), hidden=True),
        TableCol(name='office', caption=_('Office')),
        TableCol(name='avg_mark', caption=_('Average mark'), hidden=True),
        TableCol(name='test_result_basic', caption=_('Basic test result'), hidden=True),
        TableCol(name='test_result_prof', caption=_('Prof. test result'), hidden=True),
        TableCol(name='opponents', caption=_('Opponents'), hidden=True),
        TableCol(name='friends', caption=_('Friends'), hidden=True),
        TableCol(name='comment', caption=_('Comment'), hidden=True),
        TableCol(name='ei_comment', caption=_('Admin comment'), hidden=True),
        TableCol(name='payment', caption=_('Amount'), hidden=True),
        TableCol(name='payment_date', caption=_('Payment date'), hidden=True),
        TableCol(name='trend', caption=_('Trend'), hidden=True),
        ]

    edit_fields = AgreementController.edit_fields
    view_fields = AgreementController.view_fields
    item_tabs = [EducationInfoTab()]

    mass_actions_class_names = [
        'MAMigrationGroupInclusion',
        'MAGroupTransferWithoutOrder',
        'MAFillPlans',
        ]

    def __init__(self):
        LookupController.__init__(self,
            data_source=TableLookupDataSource('student_migration_for_admin'),
            columns=self.lookup_columns,
            title=self.model_object.model_title,
            mass_actions_class=model.StudentAgreement,
            mass_actions_class_names=self.mass_actions_class_names,
        )
        CRUDController.__init__(self, model_object=self.model_object)
        self.title = _("Migration for admin")
        self.local_menu = []

exposed = MigrationForAdminController()
